package com.lagou.sqlSession;

import com.lagou.mapping.SqlCommandType;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;

import java.lang.instrument.IllegalClassFormatException;
import java.lang.reflect.*;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    private Executor simpleExecutor;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.simpleExecutor = new SimpleExecutor(configuration);
    }

    @Override
    public <E> List<E> selectList(String statementid, Object... params) throws Exception {
        //将要去完成对simpleExecutor里的query方法调用
//        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementid);
        List<Object> list = simpleExecutor.query(mapperStatement, params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementid, Object... params) throws Exception {
        List<Object> objects = selectList(statementid, params);
        if(objects.size() == 1){
            return (T) objects.get(0);
        }else{
            throw new RuntimeException("查询结果为空或者查询结果过多");
        }
    }

    @Override
    public int update(String statementid, Object parameter) throws Exception {
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementid);
        return simpleExecutor.update(mapperStatement, parameter);
    }

    @Override
    public int deleteById(String statementid, Integer id) throws Exception {
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementid);
        return simpleExecutor.deleteById(mapperStatement, id);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理来为Dao接口生成代理对象
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层还是执行JDBC代码    根据不同情况调用selectList或selectOne
                //准备参数 1. statementid:sql语句唯一标识:namespace.id=接口全限定名.方法名

                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();

                String statementId = className + "." + methodName;

                MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
                if(mapperStatement != null){
                    SqlCommandType sqlCommandType = mapperStatement.getSqlCommandType();
                    switch (sqlCommandType){
                        case SELECT:
                            //准备参数 2. params:args
                            // 获取被调用方法返回值类型
                            Type genericReturnType = method.getGenericReturnType();
                            //判断是否进行了泛型参数化
                            if(genericReturnType instanceof ParameterizedType){
                                List<Object> list = selectList(statementId, args);
                                return list;
                            }
                            return selectOne(statementId, args);
                        case UPDATE:
                            if(args.length > 0){
                                return update(statementId, args[0]);
                            }else{
                                throw new NullPointerException("参数为空,你确定不是来捣乱的吗？");
                            }
                        case DELETE:
                            if(args.length > 0){
                                Class<?> aClass = args[0].getClass();
                                if(args[0] instanceof Integer){
                                    return deleteById(statementId, (int) args[0]);
                                }else{
                                    throw new IllegalClassFormatException("参数传入不对");
                                }
                            }else{
                                throw new NullPointerException("参数为空,你确定不是来捣乱的吗？");
                            }

                    }
                }

                throw new RuntimeException("方法异常,未来解析到该方法statementid");
            }
        });
        return (T) proxyInstance;
    }
}
